<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary" @click="setaddress = true">修改密码</a-button>
      </div>
    </div>
    <el-dialog class="school-form" title="修改密码" width="510px" :visible.sync="setaddress">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
        <el-form-item label="原密码" prop="password2">
          <el-input v-model="ruleForm.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="ruleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password1">
          <el-input v-model="ruleForm.password1" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button @click="setaddress = false" size="mini">取 消</el-button>
      </div>
    </el-dialog>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <table class="table table-borderless">
          <tbody>
            <tr>
              <td width="100" class="text-right">姓名</td>
              <td>{{getuser.name}}</td>
              <td width="100" class="text-right">性别</td>
              <td>{{getuser.sex}}</td>
              <td width="180" rowspan="3">
                <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="true"
                  :multiple="false"
                  accept="*/image"
                  :auto-upload="false"
                  :http-request="ossuploadimage"
                  ref="upload"
                  :limit="1"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="getuser.headimg" :src="getuser.headimg" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </td>
            </tr>
            <tr>
              <td width="100" class="text-right">手机号</td>
              <td>{{getuser.phonenum}}</td>
              <td width="100" class="text-right">是否授课</td>
              <td>{{getuser.isteacher?'是':'否'}}</td>
            </tr>
            <tr>
              <td width="100" class="text-right">授课范围</td>
              <td>{{clazz }}</td>
              <td width="100" class="text-right">校区</td>
              <td>{{address}}</td>
            </tr>
            <tr>
              <td colspan="4" class="text-right"></td>
              <td class="text-center">
                <el-button @click="submit" type="primary">修改头像</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asyncchangeschooluser,
  asynccreatepassword,
  ossupload
} from "../../../../plugins/api.js";
import OSS from "ali-oss";
import uuid from "uuid/v4";
export default {
  name: "myhome",
  data() {
    const ispassword = (rule, value, callback) => {
      const reg = new RegExp(/^[A-Za-z0-9]+$/);
      if (!reg.test(value)) {
        callback(new Error("密码只支持数字和字母"));
      } else {
        callback();
      }
    };
    const ispassword1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      setaddress: false,
      ruleForm: {
        ID: "",
        password1: "",
        password2: "",
        password: ""
      },
      rules: {
        password1: [
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          },
          { required: true, validator: ispassword1, trigger: "blur" }
        ],
        password2: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          }
        ],
        password: [
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          },
          { required: true, validator: ispassword, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.ruleForm.ID = this.getuser.ID;
  },
  computed: {
    ...mapGetters(["getuser", "getschooladdress"]),
    clazz() {
      const { getuser, getschooladdress } = this;
      if (getuser.isteacher) {
        if (getuser.classscope == "*") return "全部校区";
        return getschooladdress
          .filter(v => String(getuser.classscope).includes(v.ID))
          .map(v => v.name)
          .join(",");
      }
      return "";
    },
    address() {
      const { getuser, getschooladdress } = this;
      if (getuser.schooladdressid) {
        return getschooladdress
          .filter(v => v.ID == getuser.schooladdressid)
          .map(v => v.name)
          .join(",");
      }
      return "全部校区";
    }
  },
  methods: {
    async ossuploadimage(e) {
      try {
        const res = await ossupload();
        const client = new OSS({
          region: "oss-cn-qingdao",
          accessKeyId: res.accessKeyId,
          accessKeySecret: res.accessKeySecret,
          stsToken: res.securityToken,
          bucket: "cdn-hterobot"
        });
        const x = e.file.name.split(".");
        const name = x[x.length - 1];
        const url = `school/head/${uuid()}.${name}`;
        await client.put(`${url}`, e.file);

        await asyncchangeschooluser({
          ID: this.getuser.ID,
          headimg: `https://cdn.hterobot.com/${url}`,
          schooladdressid: this.getuser.schooladdressid
        });
        await this.$store.dispatch("session");
        this.$message.success("修改成功, 重新登录生效");
      } catch (e) {
        console.error("error: %j", e);
      }
    },
    async submitForm() {
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          try {
            await asynccreatepassword(this.ruleForm);
            this.setaddress = false;
            this.$message.success(`修改成功`);
            window.location.reload()
          } catch (err) {
            this.$message.error(`修改失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    },
    submit() {
      this.$refs.upload.submit();
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>